package com.neusoft.bizcore.license.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import com.neusoft.bizcore.license.annotation.LicenseNotRequired;
import com.neusoft.bizcore.license.service.LicenseVerifyService;

/**
 * 拦截器
 *
 * @author suncf
 */
public class LicenseCheckInterceptor implements HandlerInterceptor {

    @Autowired
    private LicenseVerifyService licenseVerifyService;

    public LicenseCheckInterceptor() {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Method method = handlerMethod.getMethod();
            final LicenseNotRequired annotation = method.getAnnotation(LicenseNotRequired.class);
            if (annotation == null) {
                //校验证书是否有效
                final boolean verifyResult = this.licenseVerifyService.isVerified();
                if (verifyResult) {
                    return true;
                } else {
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    response.setCharacterEncoding("utf-8");
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write("{\"status\":\"failure\",\"data\":\"授权证书无效，请核查服务器是否取得授权或重新申请证书。\"}");
                    return false;
                }

            }
        }
        return true;
    }
}
